import type { PageType } from '../../../../../lib/page_handler/type'
import type {
  BaseStyleConfig,
  IPersonalizationItemConfig,
  PlatformTypeValue,
} from '../../../../../types/interfaces'
import { RangeSlider } from '../../../../../components/range_slider'
import { UserPref } from '../../../../../lib/abstract'
import { BaiduPageType } from '../../../../../lib/page_handler/platform/baidu/types'
import { SUPPORTED_PLATFORMS, VALID_RESULT } from '../../../../../types/constants'

export class SearchResultNum extends UserPref {
  readonly id = 'search_result_num'
  readonly name = 'SearchResultNum'
  readonly styleConfigKey = 'searchResultNum'
  readonly supportedPages: Partial<Record<PlatformTypeValue, PageType[]>> | '*' = {
    [SUPPORTED_PLATFORMS.BAI_DU]: [
      BaiduPageType.Web,
      BaiduPageType.News,
      BaiduPageType.Video,
    ],
  }

  readonly cssProperty = ''
  readonly cssValueSuffix = ''
  private readonly defaultMinResultNum: number = 10
  private readonly defaultMaxResultNum: number = 50

  // 关闭空的样式元素
  readonly enableEmptyStyleElement: boolean = false
  // 启用页面类型隔离
  usePageTypeIsolation = true

  constructor(config: IPersonalizationItemConfig) {
    super(config)
  }

  createComponent(config: BaseStyleConfig, value: string, _mode: string, debouncedSave: (() => void) & { flush: () => void }): RangeSlider {
    const id = this.generateId(config.styleVar)
    const remark = config.remark || ''
    return new RangeSlider({
      id,
      label: '显示条数',
      value: this.getLimitedValue(Number(value) || this.defaultMinResultNum),
      min: this.defaultMinResultNum,
      max: this.defaultMaxResultNum,
      step: 1,
      title: remark,
      onChange: (value) => {
        this.cachedValues.set(id, String(value))
        debouncedSave()
      },
      showValue: true,
    })
  }

  /**
   * 获取动态限制后的值
   */
  private getLimitedValue(value: number): number {
    return Math.min(value, this.defaultMaxResultNum)
  }

  // 由于直接使用的是 input[type="range"] 传递的值，所以不需要额外的校验逻辑
  handleCheck(value: string): { status: ValidResultType, error: string } {
    if (!value || value.length === 0)
      return { status: VALID_RESULT.SKIP.value, error: '' }
    return { status: VALID_RESULT.VALID.value, error: '' }
  }
}
